package design.responsibility.demo01;

import java.util.Optional;

/**
 * <p>
 * abstract handler
 * </P>
 *
 * @author dingwen
 * @date 2021.10.15 10:31
 */
public abstract class AbstractHandler {
    /**
     * 下一个处理程序
     */
    private AbstractHandler nextHandler;

    public void setNextHandler(AbstractHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    /**
     * 处理程序
     *
     * @param request 请求
     * @return {@link Response}
     */
    public final Response handler(Request request) {
        if (this.getLevel().above(request.getLevel())) {
            return this.response();
        }
        return Optional.ofNullable(nextHandler)
                .orElseThrow(() -> new RuntimeException("没有合适的处理器处理~"))
                .handler(request);
    }

    /**
     * 响应
     *
     * @return {@link Response}
     */
    protected abstract Response response();

    /**
     * 得到水平
     *
     * @return {@link Level}
     */
    protected abstract Level getLevel();
}
